package xjson

import (
	"github.com/json-iterator/go"
	"github.com/json-iterator/go/extra"
	"log/slog"
	"strings"
	"unicode"
)

var (
	json    = jsoniter.ConfigCompatibleWithStandardLibrary
	Marshal = json.Marshal

	Unmarshal = json.Unmarshal

	MarshalIndent = json.MarshalIndent

	NewDecoder = json.NewDecoder

	NewEncoder = json.NewEncoder

	Valid = json.Valid

	Get = json.Get

	MarshalString = json.MarshalToString

	UnmarshalFromString = json.UnmarshalFromString
)

func init() {
	extra.RegisterFuzzyDecoders()
	extra.SetNamingStrategy(CamelCase)
}

func CamelCase(name string) string {
	if strings.ToUpper(name) == name {
		return strings.ToLower(name)
	}
	l := len(name)
	if l < 2 {
		return strings.ToLower(name)
	}

	return string(unicode.ToLower(rune(name[0]))) + name[1:l-1] + string(unicode.ToLower(rune(name[l-1])))
}

func MarshalStringWithDefault(val any, def string) string {
	str, err := MarshalString(val)
	if err != nil {
		slog.Error("MarshalStringWithDefault fail", "err", err)
		str = def
	}
	return str
}
